<?php

namespace App\Http\Controllers;

use App\Business\BLL\Wechat\MiniProgram;
use App\Models\ChallengeGame;
use App\Models\CityList;
use App\Models\SectMember;
use App\Models\Subscribe;
use App\Models\WechatUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Overtrue\EasySms\EasySms;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class WechatUserController extends Controller
{
    public function signup()
    {
        $code = request()->input('code', '');
        $iv = request()->input('iv', '');
        $encryptData = request()->input('encrypted_data', '');

        if ($code == '') {
            return response()->json(['recode' => 0, 'msg' => '缺少code']);
        }
        $miniProgram = MiniProgram::make();
        $wechatUserInfo = $miniProgram->auth->session($code);
        if (!array_key_exists('openid', $wechatUserInfo)) {
            return response()->json(['recode' => 0, 'msg' => $wechatUserInfo['errmsg']]);
        }
        $openid = $wechatUserInfo['openid'];
        $session = $wechatUserInfo['session_key'];
        $decryptedData = $miniProgram->encryptor->decryptData($session, $iv, $encryptData);
        $unionId = $decryptedData['unionId'];
        $name = $decryptedData['nickName'];
        $headImg = $decryptedData['avatarUrl'];
        $userInfo = WechatUser::firstOrCreate(['unionid' => $unionId], ['openid' => $openid, 'name' => $name, 'head_img' => $headImg]);
        if (empty($userInfo->openid)) {
            $userInfo->openid = $openid;
            $userInfo->save();
        }
        return response()->json(['recode' => 1, 'userinfo' => $userInfo]);

    }

    public function login()
    {
        $code = request()->input('code', '');
        if ($code == '') {
            return response()->json(['recode' => 0, 'msg' => '缺少code']);
        }
        $miniProgram = MiniProgram::make();
        $wechatUserInfo = $miniProgram->auth->session($code);
        if (!array_key_exists('openid', $wechatUserInfo)) {
            return response()->json(['recode' => 0, 'msg' => $wechatUserInfo['errmsg']]);
        }
        $openid = $wechatUserInfo['openid'];

        $userInfo = WechatUser::where('openid', $openid)->first();
        if ($userInfo) {
            return response()->json(['recode' => 1, 'userinfo' => $userInfo]);
        } else {
            return response()->json(['recode' => 0, 'msg' => "用户未注册"]);
        }
    }

    public function makeBarcode()
    {
        $openid = request()->input('openid');
        $userInfo = WechatUser::where('openid', $openid)->first();
        if ($userInfo === null) {
            return response()->json(['recode' => 0, 'msg' => '用户不存在']);
        }
        //产生身份二维码
        $barcodeName = 'user_' . $openid . '.png';
        $context = time() . '&1&' . $userInfo->id;
        $context = base64_encode($context);
        if (empty($userInfo->head_img)) {
            QrCode::encoding('UTF-8')->errorCorrection('H')->format('png')->size(200)->margin(0)->generate($context, public_path('uploads/barcode/') . $barcodeName);
        } else {
            QrCode::encoding('UTF-8')->errorCorrection('H')->format('png')->size(200)->margin(0)->merge($userInfo->head_img, .2, true)->generate($context, public_path('uploads/barcode/') . $barcodeName);

        }
        $userInfo->id_barcode = $barcodeName;
        $userInfo->save();
        $sectMember = SectMember::where('user_id', $userInfo->id)->first();
        if ($sectMember) {
            $sect = [
                'sect_id' => $sectMember->sect_id,
                'sect_title' => $sectMember->title,
                'sect_name' => $sectMember->sect->name,
                'sect_short_name' => $sectMember->sect->short_name,
            ];
        } else {
            $sect = [
                'sect_id' => 0,
                'sect_title' => 100,
                'sect_name' => '未加入门派',
                'sect_short_name' => '未加入门派',
            ];
        }

        return response()->json(['recode' => 1, 'userinfo' => $userInfo, 'sect' => $sect]);
    }

    public function sendRandCode()
    {
        $tele = request()->input('tele', "");
        if ($tele == "") {
            return response()->json([
                'recode' => 0,
                'msg' => "手机号码不能为空",
            ]);
        }

        $code = strval(mt_rand(0, 9)) . strval(mt_rand(0, 9)) . strval(mt_rand(0, 9)) . strval(mt_rand(0, 9)) . strval(mt_rand(0, 9)) . strval(mt_rand(0, 9));

        $config = config('sms');
        $easySms = new EasySms($config);
        $easySms->send($tele, [
            'content' => '您的验证码为: ' . $code,
            'template' => 'SMS_165360429',
            'data' => [
                'code' => $code,
            ],
        ]);

        // $context = config('message.sign') . "您的验证码为:" . $code;

        // $sendClass = new SendMsg();
        // $res = $sendClass->send($tele, $context);
        // $res = json_decode($res, true);

        // if (!$res['success']) {
        //     return response()->json([
        //         'recode' => 0,
        //         'msg' => "短信发送失败,请稍后再试",
        //     ]);
        // }

        //缓存验证码,有时间5分钟
        \Cache::put($tele, $code, 5);

        return response()->json([
            'recode' => 1,
            'msg' => "发送成功",
            'code' => "",
        ]);
    }

    public function updateTele()
    {
        $id = request()->input('id', "");
        $city = request()->input('city', "");
        $tele = request()->input('tele', "");
        $code = request()->input('code', "");

        if ($tele == "" || $code == "") {
            return response()->json([
                'recode' => 0,
                'msg' => "手机号码和验证码不能为空",
            ]);
        }

        $oldCode = \Cache::get($tele, '');
        if ($oldCode == "") {
            return response()->json([
                'recode' => 0,
                'msg' => "验证码失效",
            ]);
        }
        if ($code != $oldCode) {
            return response()->json([
                'recode' => 0,
                'msg' => "验证码错误",
            ]);
        }

        $user = WechatUser::find($id);
        $user->tele = $tele;
        $user->city = $city;

        $user->save();
        return response()->json([
            'recode' => 1,
            'msg' => "更新成功",
            'user' => $user,
        ]);
    }

    public function updateInfo(Request $request)
    {
        $file = $request->file("file");
        $id = request()->input('id', "");
        $nickname = request()->input('nickname', "");
        $name = request()->input('name', "");
        $style = request()->input('style', "");
        $weapon = request()->input('weapon', "");
        $scoreFlag = request()->input('score_flag', "");
        $city = request()->input('city', "");

        $user = WechatUser::find($id);

        if ($nickname !== "") {
            //检查昵称是否重复
            $duplicate = WechatUser::where([['nickname', $nickname], ['id', '!=', $id]])->first();
            if ($duplicate) {
                return response()->json([
                    'recode' => 0,
                    'msg' => "江湖名号已经存在，请换一个",
                ]);

            }
            $user->nickname = $nickname;
        }
        if ($name !== "") {
            $user->name = $name;
        }
        if ($style !== "") {
            $user->style = $style;
        }
        if ($weapon !== "") {
            $user->weapon = $weapon;
        }
        if ($scoreFlag !== "") {
            $user->score_flag = $scoreFlag;
        }
        if ($city !== "") {
            $user->city = $city;
        }
        //保存图片
        if ($file) {
            $disk = \Storage::disk('qiniu');
            if ($user->head_file) {
                $disk->delete($user->head_file);
            }

            $headAvatar = $disk->put('user', $file);
            $user->head_file = $headAvatar;
            $user->head_img = $disk->url(['path' => $headAvatar, 'domainType' => 'https']);
            // $user->head_img = $disk->url(['path' => $headAvatar, 'domainType' => 'default']);
        }

        $user->save();

        return response()->json([
            'recode' => 1,
            'msg' => "更新成功",
            'user' => $user,
        ]);
    }

    public function getUserInfo()
    {
        $userId = request()->input('user_id', "");
        $userAId = request()->input('usera_id', "");
        $user = WechatUser::find($userId);
        $sectMember = SectMember::where('user_id', $userId)->first();
        if ($sectMember) {
            $sect = [
                'sect_id' => $sectMember->sect_id,
                'sect_title' => $sectMember->title,
                'sect_name' => $sectMember->sect->name,
                'sect_short_name' => $sectMember->sect->short_name,
            ];
        } else {
            $sect = [
                'sect_id' => 0,
                'sect_title' => 100,
                'sect_name' => '未加入门派',
                'sect_short_name' => '未加入门派',
            ];
        }
        //写入访问记录
        $user->view = $user->view + 1;
        $user->save();
        //查询关注数
        $subCount = Subscribe::where('user_b', $userId)->count();
        //查询人是否关注
        $isSub = Subscribe::where([['user_a', $userAId], ['user_b', $userId]])->first();
        if ($isSub) {
            $isSub = true;
        } else {
            $isSub = false;
        }
        //计算胜率
        $totleMatch = ChallengeGame::where([['type', 1], ['status', 40]])
            ->where(function ($query) use ($userId) {
                $query->where('play_a', $userId)
                    ->orWhere('play_b', $userId);
            })
            ->count();
        $winMatch = ChallengeGame::where([['type', 1], ['status', 40]])
            ->where(function ($query) use ($userId) {
                $query->whereRaw('play_a=? and score_a>score_b', [$userId])
                    ->orWhereRaw('play_b=? and score_b>score_a', [$userId]);

            })
            ->count();
        $winRate = 100;
        if ($totleMatch > 0) {
            $winRate = intval(round($winMatch / $totleMatch, 2) * 100);
        }
        //将视频及图片转换为json
        $video = \json_decode($user->video, true);
        $user->video = $video ? $video : [];
        $image = \json_decode($user->image, true);
        $user->image = $image ? $image : [];

        return response()->json([
            'recode' => 1,
            'user' => $user,
            'sect' => $sect,
            'subcount' => $subCount,
            'issub' => $isSub,
            'winrate' => $winRate,
        ]);

    }

    public function getUserInfoSample()
    {
        $userId = request()->input('user_id', "");
        $user = WechatUser::find($userId);
        $sectMember = SectMember::where('user_id', $userId)->first();
        if ($sectMember) {
            $sect = [
                'sect_id' => $sectMember->sect_id,
                'sect_title' => $sectMember->title,
                'sect_name' => $sectMember->sect->name,
                'sect_short_name' => $sectMember->sect->short_name,
            ];
        } else {
            $sect = [
                'sect_id' => 0,
                'sect_title' => 100,
                'sect_name' => '未加入门派',
                'sect_short_name' => '未加入门派',
            ];
        }

        return response()->json([
            'recode' => 1,
            'user' => $user,
            'sect' => $sect,
        ]);

    }

    public function getMyRanking()
    {
        $type = request()->input('type', 'point');
        $userId = request()->input('user_id', 0);
        $city = request()->input('city', '');
        $city = rtrim($city, '0');

        //修改江湖排行榜地区排名和全国排名
//        $user = WechatUser::where('city', 'like', $city)->find($userId);
        $user = WechatUser::find($userId);
//        $city = rtrim($user->city, '0');
        if (strlen($city) % 2 === 1) {
            $city = $city . '0';
        }
        $city .= '%';
        $ranking = 0;
        $nationwideing = 0;
        $mycityname = '请先到个人中心定位';
        if ($user) {
            if ($type == "point") {
                $score_flag = '';
            } else {
                $score_flag = 'and score_flag=1';
            }

            //查询个人地区排名
            $userrank = DB::select("SELECT b.* FROM (SELECT t.*, @rownum := @rownum + 1 AS rownum FROM (SELECT @rownum := 0) r,
                    (SELECT id,nickname,name,head_img,point,score,is_true FROM `wechat_users` where (city like '$city' or id=" . $userId . ")" . $score_flag . "  ORDER BY " . $type . " desc,is_true desc) as t 
) as b where b.id = " . $userId);
            $nationwide = DB::select("SELECT b.* FROM (SELECT t.*, @rownum := @rownum + 1 AS rownum FROM (SELECT @rownum := 0) r,
                    (SELECT id,nickname,name,head_img,point,score,is_true FROM `wechat_users` where 1=1 " . $score_flag . " ORDER BY " . $type . " desc,is_true desc) as t 
) as b where b.id = " . $userId);
            if ($userrank) {
                $ranking = $userrank[0]->rownum;
            }
            if ($nationwide) {
                $nationwideing = $nationwide[0]->rownum;
            }
            if ($city) {
                $mycity = CityList::where([['key', 'like', $city]])->first();
                $mycityname = $mycity->name;
            }


            //查询个人地区排名
//            $rank = WechatUser::where([['city', 'like', $city], ['is_true', 1]])
//                ->orderBy($type, 'desc')
//                ->orderBy('is_true', 'desc');
//            if ($city){
//                $mycity=CityList::where([['key','like',$city]])->first();
//                $mycityname=$mycity->name;
//            }
//            //全国
//            $nationwide = WechatUser::where([['is_true', 1]])
//                ->orderBy($type, 'desc')
//                ->orderBy('is_true', 'desc');
//            if ($type == "point") {
//                $rank = $rank->where($type, '>', $user->point)->count();
//                $nationwide = $nationwide->where($type, '>', $user->point)->count();
//                $ranking = $rank + 1;
//                $nationwideing = $nationwide + 1;
//            } else {
//                if ($user->score_flag) {
//                    $rank = $rank->where([['score_flag', 1], [$type, '>', $user->score]])->count();
//                    $nationwide = $nationwide->where($type, '>', $user->score)->count();
//                    $ranking = $rank + 1;
//                    $nationwideing = $nationwide + 1;
//                }
//            }
            $ret = ['recode' => 1,
                'ranking' => $ranking,
                'nationwideing' => $nationwideing,
                'mycityname' => $mycityname,
                'info' => [
                    'head_img' => $user->head_img,
                    'nickname' => $user->nickname,
                    'name' => $user->name,
                    'point' => $user->point,
                    'score' => $user->score,
                ],
            ];
        } else {
            $ret = ['recode' => 1,
                'ranking' => $ranking,
            ];
        }

        return response()->json($ret);

    }

    public function getUserRanking()
    {
        $pn = request()->input('pn', config('api.page_num'));
        $type = request()->input('type', 'point');
        //搜索全国，去除地区字段
        $city = request()->input('city', '');
        $user_id = request()->input('user_id');
        $seach = request()->input('seach');
        if ($seach!=1){
            $city = rtrim($city, '0');
            if (strlen($city) % 2 === 1) {
                $city = $city . '0';
            }
            $city .= '%';
        }
        $keyword = request()->input('keyword', '');
        $keyword = '%' . $keyword . '%';
        if ($seach!=1){
            $list = WechatUser::where('city', 'like', $city)
                ->where(function ($query) use ($keyword) {
                    $query->where('name', 'like', "%{$keyword}%")
                        ->orWhere('nickname', 'like', "%{$keyword}%");
                })
                ->with(['sectMember:sect_id,user_id,title', 'sectMember.sect:id,short_name as name'])
                ->select('id', 'nickname', 'name', 'head_img', 'point', 'score');
        }else{
            $list = WechatUser::where(function ($query) use ($keyword) {
                    $query->where('name', 'like', "%{$keyword}%")
                        ->orWhere('nickname', 'like', "%{$keyword}%");
                })
                ->with(['sectMember:sect_id,user_id,title', 'sectMember.sect:id,short_name as name'])
                ->select('id', 'nickname', 'name', 'head_img', 'point', 'score');
        }
        if ($type == "score") {
            $list = $list->where('score_flag', 1);
        }
        $list = $list
            ->orderBy($type, 'desc')
            ->orderBy('is_true', 'desc')
            ->paginate($pn);
        foreach ($list as $key => $value) {
            //查询人是否关注
            $isSub = Subscribe::where([['user_a', $user_id], ['user_b', $value['id']]])->first();
            if ($isSub) {
                $isSub = true;
            } else {
                $isSub = false;
            }
            $value['isSub'] = $isSub;
        }
        $ret = ['recode' => 1,
            'data' => ['last_page' => $list->lastPage()
                , 'page' => $list->currentPage()
                , 'list' => $list->items()],
        ];
        return response()->json($ret);

    }

    public function updateStatus(Request $request)
    {
        $id = request()->input('id', 0);
        $status = request()->input('status', '');
        $imgUrls = request()->input('imgurls', '');
        $videoUrls = request()->input('videourls', '');
        $del = request()->input('del');
        //删除旧资料
        foreach ($del as $vo) {
            $disk = \Storage::disk('qiniu');
            $disk->delete($vo['path']);
        }
        //保存
        $imgUrls = \json_encode($imgUrls);
        $videoUrls = \json_encode($videoUrls);
        WechatUser::where('id', $id)->update(['personal_status' => $status, 'video' => $videoUrls, 'image' => $imgUrls]);

        return response()->json(['recode' => 1, 'msg' => '保存成功']);

    }

}
